<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
import { login as loginApi } from '@/api/user'
import { setToken } from '@/utils/auth'
import { getPermissionCodesByUserId } from '@/api/permission'
import { getUserMenuTree } from '@/api/permission'

const router = useRouter()
const userStore = useUserStore()
const isRegister = ref(false)
const form = ref()

const login = async () => {
  await form.value.validate()
  try {
    console.log('登录页 - 开始登录:', formModel.value.username)

    // 直接调用API而不是userStore.login，避免Pinia代理问题
    const response = await loginApi(formModel.value)
    console.log('登录页 - 登录API响应:', response)

    if (response.data.code === 1) {
      const { token, id, userName, name } = response.data.data
      console.log('登录页 - 登录成功，设置用户信息:', {
        token,
        id,
        userName,
        name
      })

      // 手动设置token和用户信息
      setToken(token)
      userStore.token = token
      userStore.userId = id
      userStore.userName = userName
      userStore.name = name

      // 保存用户信息到localStorage
      localStorage.setItem('user_info', JSON.stringify({ id, userName, name }))

      // 手动获取权限
      console.log('登录页 - 开始获取权限')
      const permResponse = await getPermissionCodesByUserId(id)
      console.log('登录页 - 权限API响应:', permResponse)

      if (permResponse.data && permResponse.data.code === 1) {
        const permissions = permResponse.data.data || []
        console.log('登录页 - 获取到权限:', permissions)

        // 使用splice方法更新权限数组
        userStore.permissions.splice(
          0,
          userStore.permissions.length,
          ...permissions
        )

        // 同时保存到localStorage
        localStorage.setItem('user_permissions', JSON.stringify(permissions))
      }

      // 手动获取菜单
      console.log('登录页 - 开始获取菜单')
      const menuResponse = await getUserMenuTree()
      console.log('登录页 - 菜单API响应:', menuResponse)

      if (menuResponse.data && menuResponse.data.code === 1) {
        const menus = menuResponse.data.data || []
        console.log('登录页 - 获取到菜单:', menus)

        // 使用splice方法更新菜单数组
        userStore.menus.splice(0, userStore.menus.length, ...menus)

        // 同时保存到localStorage
        localStorage.setItem('user_menus', JSON.stringify(menus))
      }

      ElMessage.success('登录成功')
      router.push('/home')
    } else {
      ElMessage.error(response.data.msg || '登录失败')
    }
  } catch (e) {
    console.error('登录页 - 登录失败:', e)
    ElMessage.error(e?.msg || '登录失败')
  }
}

const formModel = ref({
  username: '',
  password: '',
  repassword: ''
})
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是 5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})
</script>

<template>
  <!--  el-row表示一行,一行分成24份 
          el-col表示列      :span="12"表示在一行中占12列  登录图占一半
          登录框占6份，两边各占 3份。
          el-form代表整个表单  一个item代表一行  ，el-input表单元素(输入框,复选框等)
      -->
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!--注册相关表单 v-if="isRegister"来显示表单 , 
      并且使用 :model绑定 formModel 对象 ，目的是让每一行可以绑定对象里的属性
      还使用 :rules="" 绑定自定义的规则对象，目的还是让每一行可以绑定规则对象里的属性-->
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
        :model="formModel"
        :rules="rules"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <!-- :prefix-icon 这个是每一个框前面的图标 -->
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录相关表单 v-else来显示表单-->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: var(--background-color);

  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 50% center / 500px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
    box-shadow: 5px 0 15px rgba(0, 0, 0, 0.1);
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: -10%;
      left: -10%;
      width: 120%;
      height: 120%;
      background: url('@/assets/pattern.svg') repeat;
      opacity: 0.1;
      animation: pattern-move 60s linear infinite;
    }
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    padding: 0 30px;

    h1 {
      color: var(--primary-dark);
      margin-bottom: 30px;
      font-size: 28px;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: -10px;
        left: 0;
        width: 50px;
        height: 4px;
        background-color: var(--primary-color);
        border-radius: 2px;
      }
    }

    .button {
      width: 100%;
      height: 50px;
      border-radius: 8px;
      font-size: 16px;
      background: linear-gradient(
        to right,
        var(--primary-color),
        var(--primary-dark)
      );
      border: none;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(60, 148, 116, 0.3);
      }
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 0 0 1px #e0e0e0;
      padding: 4px 15px;
      transition: all 0.3s;

      &:hover,
      &.is-focus {
        box-shadow: 0 0 0 1px var(--primary-color);
      }

      .el-input__inner {
        height: 40px;
      }
    }

    :deep(.el-form-item) {
      margin-bottom: 25px;
    }

    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }

    :deep(.el-link.el-link--primary) {
      color: var(--primary-color);

      &:hover {
        color: var(--primary-dark);
      }
    }
  }
}

@keyframes pattern-move {
  0% {
    transform: translateX(0) translateY(0);
  }
  100% {
    transform: translateX(-20%) translateY(-20%);
  }
}
</style>
